package com.guoqi.keepsign.ligui

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import com.guoqi.keepsign.IPConfig
import com.guoqi.keepsign.R
import com.guoqi.keepsign.album.AlbumAdapter
import com.guoqi.keepsign.base.ImageInfo
import com.guoqi.keepsign.utils.ThreadPoolManager
import kotlinx.android.synthetic.main.fm_common.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document


class LiguiAlbumUI : AppCompatActivity() {

    val TAG = "LiguiUI"

    private lateinit var pageList: ArrayList<String>
    private var mList: ArrayList<ImageInfo>? = null
    private var albumAdapter: AlbumAdapter? = null
    private var gm: GridLayoutManager? = null
    private val mHandler = @SuppressLint("HandlerLeak")
    object : android.os.Handler() {
        override fun handleMessage(msg: android.os.Message) {
            albumAdapter?.notifyDataSetChanged()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fm_common)
        mSwipeRefresh.isEnabled = false
        initUI()
    }

    private fun initUI() {
        pageList = intent.getStringArrayListExtra("pageList")
        gm = GridLayoutManager(this, 2)
        mRvCommonList.layoutManager = gm
        mRvCommonList.setHasFixedSize(true)
        mList = ArrayList()
        albumAdapter = AlbumAdapter(this, mList!!, mRvCommonList.layoutManager as GridLayoutManager)
        mRvCommonList.adapter = albumAdapter
        for (pageUrl in pageList) {
            ThreadPoolManager.getInstance().execute {
                getData(pageUrl)
            }
        }

    }

    private fun getData(pageUrl: String) {
        try {
            val doc: Document = Jsoup.connect(pageUrl)
                    .timeout(IPConfig.DEFAULT_TIMEOUT).userAgent(IPConfig.DEFUALT_USERAGENT).get()
            val img = doc.getElementsByAttributeValue("border", "0")
            val url = img.attr("src")
            mList?.add(ImageInfo(url))
            Log.e(TAG, url)
            mHandler.sendEmptyMessage(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(0)
        ThreadPoolManager.getInstance().release()
        super.onDestroy()
    }
}